﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

namespace CCF20Model.ModelBase
{
    public class CustomizeTypeCollection<T> : ObservableCollection<T>
    {
        private CCF20Entities ccf20Entities;
        private string tableName;
        //List<string> pluraTable = new List<string>{"Vehicle","Device","Customer","TransferedCustomer","Fault"};
        protected override void InsertItem(int index, T item)
        {
            if (item != null)
            {
                ccf20Entities.AddObject(tableName, item);
                base.InsertItem(index, item);
            }
        }

        protected override void RemoveItem(int index)
        {
            if (this[index] is MaintenanceType)
            {
                MaintenanceType maintenanceType = this[index] as MaintenanceType;
                maintenanceType.VehicleMaintenanceRecords.ToList().ForEach(x => ccf20Entities.DeleteObject(x));
                maintenanceType.VehicleMaintenanceHistories.ToList().ForEach(x => ccf20Entities.DeleteObject(x));
            }
            ccf20Entities.DeleteObject(this[index]);
            base.RemoveItem(index);
        }
        public CustomizeTypeCollection(IQueryable<T> serviceRequest, CCF20Entities context)
            : base(serviceRequest)
        {
            Type t = typeof(T);
            if (t.Name.EndsWith("s"))
            {
                tableName = string.Concat(t.Name, "es");
            }
            else if (t.Name.EndsWith("y"))
            {
                tableName = string.Concat(t.Name.Remove(t.Name.Length - 1), "ies");
            }
            else if (t.Name.EndsWith("S"))
            {
                tableName = t.Name;
            }
            else 
            {
                tableName = string.Concat(t.Name, "s");
            }
            ccf20Entities = context;
        }

    }

}
